import 'dart:async';

import 'package:bluetooth_protocols_parser_plugin/library.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/others/manager/future_manager.dart';
import 'package:inmotion_pro/pages/mixin/protocol_mixin.dart';
import 'package:inmotion_pro/pages/mixin/web_view_mixin.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../../config/const.dart';
import '../../../custom_exception/lx_exception.dart';

class SettingHelper with ProtocolMixin, WebViewMixin {
  // 私有静态实例
  static final SettingHelper _instance = SettingHelper._internal();

  // 静态 getter
  static SettingHelper get instance => _instance;

  // 私有构造函数
  SettingHelper._internal();

  // 取消电机自适应轮询令牌
  CancelToken _cancelMotorAdaptationToken = CancelToken();

  // 电池信息
  batteryInfoOnTap() {
    Get.toNamed(AppRoutes.BATTERY_INFO);
  }

  // 关于车辆
  aboutVehicleOnTap() {
    Get.toNamed(AppRoutes.ABOUT_VEHICLE);
  }

  // MARK: - 修改车辆昵称
  updateVehicleNicknameOnTap(
    String currentNickname, {
    required Function(String) onSetCompleted,
  }) {
    LxAlert.show(
      local.modify_vehicle_nickname,
      textFieldValue: currentNickname,
      maxLength: vehicleNicknameMaxLength,
      inputType: InputType.email,
      confirmCallback: (nickname) {
        Loading.showLoading(null);
        protocolMixinChangeVehicleNickname(nickname).then((success) {
          if (success) {
            if (nickname != null) {
              onSetCompleted(nickname);
            }
            Loading.showSuccess(local.setting_successful);
          } else {
            Loading.showError(local.setting_failed);
          }
        }).catchErrorHandler();
      },
      confirmTitle: local.confirm,
      cancelTitle: local.cancel,
    );
  }

  // MARK: - 车辆锁车密码
  vehiclePasswordOnTap() {
    Loading.showLoading(null);
    protocolMixinGetVehiclePassword().then((oldPassword) {
      debugPrint("当前车辆密码：$oldPassword");
      Loading.dismiss();
      LxAlert.show(
        local.modify_vehicle_password,
        textFieldValue: oldPassword,
        textFieldPlaceholder: local.modify_vehicle_password_placeholder,
        inputType: InputType.number,
        maxLength: vehiclePasswordLength,
        isShowSecret: true,
        isSecret: true,
        confirmCallback: (pwd) {
          Loading.showLoading(null);
          protocolMixinChangeVehiclePassword(pwd).then((success) {
            if (success) {
              Loading.showSuccess(local.setting_successful);
            } else {
              Loading.showError(local.setting_failed);
            }
          }).catchErrorHandler();
        },
        confirmTitle: local.confirm,
        cancelTitle: local.cancel,
      );
    }).catchErrorHandler();
  }

  // MARK: - 设置限速翘板，单位 0.01km/h
  setSpeedLimitOnTap(
    double limitSpeed,
    double warningSpeed, {
    required Function(double, double) onSetCompleted,
  }) {
    Loading.showLoading(null);
    protocolMixinSetSpeedLimitTiltBack(limitSpeed).then((success) {
      if (warningSpeed > limitSpeed) {
        // 当警告速度大于限速翘板时，同时设置限速警告为限速翘板值, 因为告警速度必须小于限速翘板
        return protocolMixinSetSpeedLimitWarning(limitSpeed - 1);
      } else {
        return Future(() => true);
      }
    }).then((success) {
      if (success) {
        onSetCompleted(
            limitSpeed, warningSpeed > limitSpeed ? limitSpeed : warningSpeed);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 设置限速警告，单位 0.01km/h
  setSpeedWarningOnTap(double value,
      {required Function(double) onSetCompleted}) {
    Loading.showLoading(null);
    protocolMixinSetSpeedLimitWarning(value).then((success) {
      if (success) {
        onSetCompleted(value);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 设置骑行模式
  setRidingModeOnTap(int value, {required Function(int) onSetCompleted}) {
    Loading.showLoading(null);
    protocolMixinSetRidingMode(value).then((success) {
      if (success) {
        onSetCompleted(value);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 开启/关闭 动力辅助
  setRideAssistOnTap(bool enable, {required Function(bool) onSetCompleted}) {
    Loading.showLoading(null);
    protocolMixinSetRideAssistSwitch(enable).then((success) {
      if (success) {
        onSetCompleted(enable);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 设置加、减速辅助
  setAccAndBrakeAssistPercentageOnTap(
    int accAssist,
    int brakeAssist, {
    required Function(int, int) onSetCompleted,
  }) {
    Loading.showLoading(null);
    protocolMixinSetAccAndBrakeAssistPercentage(accAssist, brakeAssist)
        .then((success) {
      if (success) {
        onSetCompleted(accAssist, brakeAssist);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 设置踏板灵敏度
  setPedalSensitivityOnTap(
    int pedalSensitivity1,
    int pedalSensitivity2, {
    required Function(int, int) onSetCompleted,
  }) {
    Loading.showLoading(null);
    protocolMixinSetPedalSensitivity(pedalSensitivity1, pedalSensitivity2)
        .then((success) {
      if (success) {
        onSetCompleted(pedalSensitivity1, pedalSensitivity1);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 设置平衡零点
  setBalanceZeroOnTap(
    int angle, {
    required Function(int) onSetCompleted,
  }) {
    Loading.showLoading(null);
    protocolMixinSetBalanceAngle(angle).then((success) {
      if (success) {
        onSetCompleted(angle);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 开启/关闭 赛道倾斜角
  turnOnBermAngleMode(bool enable, {required Function(bool) onSetCompleted}) {
    Loading.showLoading(null);
    protocolMixinSetBermAngleModeSwitch(enable).then((success) {
      if (success) {
        onSetCompleted(enable);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 开启/关闭 防飞转
  turnOnSpinKill(bool enable, {required Function(bool) onSetCompleted}) {
    Loading.showLoading(null);
    protocolMixinSetSpinKillSwitch(enable).then((success) {
      if (success) {
        onSetCompleted(enable);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 设置待机时间
  setStandByTimeOnTap(int time, {required Function(int) onSetCompleted}) {
    Loading.showLoading(null);
    protocolMixinSetStandByTime(time).then((success) {
      if (success) {
        onSetCompleted(time);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 开启/关闭 主声浪
  turnOnMainSound(bool enable, {required Function(bool) onSetCompleted}) {
    Loading.showLoading(null);
    protocolMixinSetMainSoundSwitch(enable).then((success) {
      if (success) {
        onSetCompleted(enable);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 设置音效包
  setSoundPackOnTap() {
    debugPrint("点击了设置音效包");
    return Future.value(true);
  }

  // MARK: - 开启/关闭 语音
  turnOnVoice(bool enable, {required Function(bool) onSetCompleted}) {
    Loading.showLoading(null);
    protocolMixinSetVoiceSwitch(enable).then((success) {
      if (success) {
        onSetCompleted(enable);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 设置音量
  setSoundVolumeOnTap(int value, {required Function(int) onSetCompleted}) {
    Loading.showLoading(null);
    protocolMixinSetSoundVolume(value).then((success) {
      if (success) {
        onSetCompleted(value);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 设置LED灯
  setLedLightOnTap() {
    debugPrint("点击了设置LED灯");
    return Future.value(true);
  }

  // MARK: - 开启/关闭 GPS控制器低电唤醒
  turnOnTBoxLowBatteryWakeupSwitchOnTap(bool enable,
      {required Function(bool) onSetCompleted}) {
    Loading.showLoading(null);
    protocolMixinSetTBoxLowBatteryWakeupSwitch(enable).then((success) {
      if (success) {
        onSetCompleted(enable);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 重启 GPS控制器
  rebootTboxOnTap() {
    LxAlert.show(
      local.rebooting_gps_controller_desc,
      title: local.tbox_reboot,
      confirmCallback: (p0) {
        Loading.showLoading(null);
        protocolMixinRebootTBox().then((success) {
          Future.delayed(const Duration(seconds: 1), () {
            if (success) {
              Loading.showSuccess(local.successed);
            } else {
              Loading.showError(local.fail);
            }
          });
        }).catchErrorHandler();
      },
      confirmTitle: local.confirm,
      cancelTitle: local.cancel,
    );
  }

  // MARK: - 开启/关闭 运输模式
  turnOnTransportModeSwitchOnTap(bool enable,
      {required Function(bool) onSetCompleted}) {
    Loading.showLoading(null);
    protocolMixinSetTransportModeSwitch(enable).then((success) {
      if (success) {
        onSetCompleted(enable);
        Loading.showSuccess(local.setting_successful);
      } else {
        Loading.showError(local.setting_failed);
      }
    }).catchErrorHandler();
  }

  // MARK: - 车辆平衡校正
  vehicleBalanceCalibrationOnTap() {
    LxAlert.show(
      local.balance_calibration_desc,
      title: local.balance_calibration,
      subContent: "(${local.vehicle_calibration_sub_desc})",
      confirmCallback: (p0) {
        Loading.showLoading(null);
        // 先进行陀螺仪校正，再进行俯仰角校正
        protocolMixinTriggerVehicleCalibration(VehicleCalibrationType.gyroscope)
            .then((success) {
          if (success) {
            // 轮询陀螺仪校正状态
            return _pollingCalibrationStatus(
                type: VehicleCalibrationType.gyroscope);
          } else {
            throw LxException(local.calibration_failed);
          }
        }).then((success) {
          if (success) {
            // 进行俯仰角校正
            return protocolMixinTriggerVehicleCalibration(
                VehicleCalibrationType.pitchAngle);
          } else {
            throw LxException(local.calibration_failed);
          }
        }).then((success) {
          if (success) {
            // 轮询俯仰角校正状态
            return _pollingCalibrationStatus(
                type: VehicleCalibrationType.pitchAngle);
          } else {
            throw LxException(local.calibration_failed);
          }
        }).then((success) {
          if (success) {
            Loading.showSuccess(local.calibration_successful);
          } else {
            Loading.showError(local.calibration_failed);
          }
        }).catchErrorHandler();
      },
      confirmTitle: local.confirm,
      cancelTitle: local.cancel,
    );
  }

  // MARK: - 车辆转向校正
  vehicleTurningCalibrationOnTap() {
    LxAlert.show(
      local.turning_calibration_desc,
      title: local.turning_calibration,
      subContent: "(${local.vehicle_calibration_sub_desc})",
      confirmCallback: (p0) {
        Loading.showLoading(null);
        // 先进行陀螺仪校正，再进行翻滚角校正
        protocolMixinTriggerVehicleCalibration(VehicleCalibrationType.gyroscope)
            .then((success) {
          if (success) {
            // 轮询陀螺仪校正状态
            return _pollingCalibrationStatus(
                type: VehicleCalibrationType.gyroscope);
          } else {
            throw LxException(local.calibration_failed);
          }
        }).then((success) {
          if (success) {
            // 进行翻滚角校正
            return protocolMixinTriggerVehicleCalibration(
                VehicleCalibrationType.rollAngle);
          } else {
            throw LxException(local.calibration_failed);
          }
        }).then((success) {
          if (success) {
            // 轮询翻滚角校正状态
            return _pollingCalibrationStatus(
                type: VehicleCalibrationType.rollAngle);
          } else {
            throw LxException(local.calibration_failed);
          }
        }).then((success) {
          if (success) {
            Loading.showSuccess(local.calibration_successful);
          } else {
            Loading.showError(local.calibration_failed);
          }
        }).catchErrorHandler();
      },
      confirmTitle: local.confirm,
      cancelTitle: local.cancel,
    );
  }

  // MARK: - 轮询校正状态
  Future<bool> _pollingCalibrationStatus({
    required VehicleCalibrationType type,
  }) {
    // 取消轮询令牌
    CancelToken cancelToken = CancelToken();
    return FutureManager.instance.pollingTask<VehicleCalibrationStatus?>(
      () {
        return protocolMixinQueryVehicleCalibrationStatus(type).then((state) {
          switch (state) {
            case VehicleCalibrationStatus.busy:
            case VehicleCalibrationStatus.calibrating:
              // 继续查询
              return state;
            default:
              // 停止查询
              cancelToken.cancel();
              return state;
          }
        });
      },
      milliseconds: 500,
      maxAttempts: 10,
      continueOnError: true,
      cancelToken: cancelToken,
    ).then((state) {
      if (state == null) {
        // 超时未返回结果
        return false;
      } else {
        switch (state) {
          case VehicleCalibrationStatus.calibrated:
            return true;
          default:
            return false;
        }
      }
    });
  }

  // MARK: - 电机自适应
  vehicleMotorAdaptationOnTap() {
    LxAlert.show(
      local.motor_self_adjustment_desc,
      title: local.motor_self_adjustment,
      subContent: "(${local.motor_self_adjustment_sub_desc})",
      confirmCallback: (p0) {
        Loading.showLoadingWithCancel(
          local.motor_self_adjustment_in_progress,
          cancelText: local.cancel,
          onCancel: () {
            Loading.showLoading(null);
            protocolMixinStopMotorSelfAdjustment().catchErrorHandler();
          },
        );
        // 先进行电机自适应
        protocolMixinTriggerMotorSelfAdjustment().then((success) {
          if (success) {
            // 轮询电机自适应状态
            return _pollingMotorAdaptationStatus().then((state) {
              switch (state) {
                case MotorAutoStatus.completed:
                  Loading.showSuccess(local.motor_self_adjustment_succeed);
                  break;
                case MotorAutoStatus.timeout:
                  Loading.showError(local.motor_self_adjustment_timeout);
                  break;
                default:
                  Loading.showError(local.motor_self_adjustment_failed);
                  break;
              }
            });
          } else {
            Loading.showError(local.motor_self_adjustment_failed);
          }
        }).catchErrorHandler();
      },
      confirmTitle: local.confirm,
      cancelTitle: local.cancel,
      extendWidget: Padding(
        padding: const EdgeInsets.only(top: 8.0),
        child: Align(
          alignment: Alignment.centerLeft,
          child: InkWell(
            onTap: () {
              LxAlert.dismiss();
              Loading.showLoading(null);
              protocolMixinClearMotorSelfAdjustmentData().then((success) {
                if (success) {
                  Loading.showSuccess(local.motor_self_adjustment_data_cleared);
                } else {
                  Loading.showError(local.fail);
                }
              }).catchErrorHandler();
            },
            child: Text(
              local.clear_motor_self_adjustment,
              style: const TextStyle(
                decoration: TextDecoration.underline,
                color: Colors.white70,
              ),
            ),
          ),
        ),
      ),
    );
  }

  // MARK: - 轮询电机自适应状态
  Future<MotorAutoStatus> _pollingMotorAdaptationStatus() {
    // 取消轮询令牌
    _cancelMotorAdaptationToken = CancelToken();
    return FutureManager.instance.pollingTask<MotorAutoStatus>(
      () {
        return protocolMixinQueryMotorSelfAdjustmentStatus().then((state) {
          switch (state) {
            case MotorAutoStatus.busy:
            case MotorAutoStatus.wait:
              // 继续查询
              return state;
            default:
              // 停止查询
              _cancelMotorAdaptationToken.cancel();
              return state;
          }
        });
      },
      milliseconds: 2000,
      maxAttempts: 60,
      continueOnError: true,
      cancelToken: _cancelMotorAdaptationToken,
    ).then((state) {
      if (state == null) {
        // 超时未返回结果
        return MotorAutoStatus.failed;
      } else {
        return state;
      }
    });
  }

  // MARK: - 自动熄屏
  vehicleAutoSleepOnTap() {
    LxAlert.show(
      "",
      title: local.auto_sleep,
      confirmCallback: (p0) {},
      confirmTitle: local.confirm,
      cancelTitle: local.cancel,
    );
  }

  // MARK: - 故障检测
  vehicleFaultDetectionOnTap() {
    Get.toNamed(AppRoutes.VEHICLE_ERROR);
  }

  // MARK: - 固件更新
  firmwareUpdateOnTap() {
    Get.toNamed(AppRoutes.FIRMWARE_UPDATE);
  }

  // MARK: - 恢复出厂设置
  restoreFactorySettingsOnTap() {
    debugPrint("点击了恢复出厂设置");
    return Future.value(true);
  }
}
